/*!
 * New Basic Strategy.
 * Date: 2015/12/31.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  'jquery',
	'pageInit',
  'dataTableFilter',
  'loading',
	'formValidator',
  'formAjax',
  'bootstrap-dialog',
  'notification',
  'listAsyncOp'
], function ($, vamakerPage, VamDataTable, VamLoader, formValidator, formAjax, BootstrapDialog, VamOpMsg, VamListOp) {
  $(function () {
    var $dataTable = $('#data-table'),
      dataUrl = VAM.getVar('CREATIVE_DATA_LIST'),
      dataLinkOp = VAM.getVar('LIST_LINK_OP_URL'),
      dataUnlinkOp = VAM.getVar('LIST_UNLINK_OP_URL'),
      $creativePreviewModal = $('#creative-preview-modal'),
      $creativePreviewIfr = $('#creative-preview-ifr'),
      $reportDataThead = $dataTable.find('thead'),
      $loadingWrap = new VamLoader().loader($('#list-loading-wrap')),
      listTable, tableOptions = {};

    tableOptions = {
      'ajax': {
        'url': dataUrl
      },
      'columns': [
        {'data': 'id'},
        {'data': 'name'},
        {'data': 'status'},
        {'data': 'creativeType'},
        {'data': 'materialType'},
        {'data': 'creativeSize'},
        {'data': 'vocation'},
        {'data': 'cost'},
        {'data': 'showCount'},
        {'data': 'clickCount'},
        {'data': 'clickRate'},
        {'data': 'cpm'},
        {'data': 'cpc'},
        {'data': 'operate'}
      ],
      'columnDefs': [
        {
          'targets': 0,
          'render': function (data, type, full, meta) {
            var ckbText = '<label><input class="ckb-children" type="checkbox" value="' + data + '"/></label>';
            ckbText = '';
            return '<p title="' + data + '">' + ckbText + data +'</p>';
          }
        },
        {
          'targets': 2,
          'render': function (data, type, full, meta) {
            var result = '';
            if (data === 'to-be-audit') {
              //result = '待审核';
              result = VAM.j('Normal');
            } else if (data === 'auditing') {
              result = VAM.j('Auditing');
            } else if (data === 'passed') {
              result = VAM.j('Passed');
            } else if (data === 'refused') {
              result = VAM.j('Refused');
            } else if (data === 'unfinished') {
              result =VAM.j('Incomplete');
            };
            return '<p title="' + result + '">' + result +'</p>';
          }
        },
        {
          'targets': [1,5,7,8,9,10,11,12],
          'render': function (data, type, full, meta) {
            return '<p title="' + data + '">' + data +'</p>'
          }
        },
        {
          'targets': 3,
          'render': function (data, type, full, meta) {
            var result = '', more = '';
            if (data === 'banner') {
              result = 'banner';
            } else if (data === 'video') {
              result = 'video';
            } else if (data === 'cpe') {
              result = 'cpe';
            }
            return '<p title="' + result + '">' + result +'</p>';
          }
        },
        {
          'targets': 4,
          'render': function (data, type, full, meta) {
            var result = '', more = '';
            if (data === 'static-pic') {
              result = VAM.j('Static Pic');
            } else if (data === 'dynamic-pic') {
              result = VAM.j('Dynamic Pic');
            } else if (data === 'swf' && full.creativeType === 'banner') {
              result = 'SWF';
            } else if (data === 'txt') {
              result = VAM.j('Text Chain');
            } else if (data === 'swf' && full.creativeType === 'video') {
              result = 'SWF';
            } else if (data === 'flv') {
              result = 'FLV';
            } else if (data === 'mp4') {
              result = 'MP4';
            }
            if (full.creativeType === 'video') {
              more = '<p title="' + full.duration + '">' + VAM.j('Duration') + '：' + full.duration +'s</p>';
            } else if (full.creativeType === 'cpe') {
              var cpeVideoType = full.cpeMaterialType.split(','),
                  videoType = [], meType = '';
              for (var i = 0; i < cpeVideoType.length; i++) {
                if (cpeVideoType[i] === 'mp4') {
                  meType = 'MP4';
                } else if (cpeVideoType[i] === 'ogg' || cpeVideoType[i] === 'ogv') {
                  meType = 'OGV';
                } else if (cpeVideoType[i] === 'webm') {
                  meType = 'WebM';
                } else if(cpeVideoType[i] === 'flv'){
                  meType = 'FLV';
                };
                videoType.push(meType);
              };
              videoType = videoType.join(',');
              more = '<p title="' + full.cpeMaterialType+ '">' + videoType +'</p>';
            };
            return '<p title="' + result + '">' + result +'</p>' + more;
          }
        },
        {
          'targets': 6,
          'render': function (data, type, full, meta) {
            var result = '', record = '', item;
            for (var i = 0, len = data.length; i < len; i++) {
              item = data[i];
              record = '<p class="text-success"><span class="label label-default">' + item['channel'] + '</span> ' + item['tags'] + '</p>';
              result += record;
            };
            return result;
          }
        },
        {
          'targets': -1,
          'render': function (data, type, full, meta) {
            return '<div class="tab-btn-group">'
                  + '<input class="row-info" type="hidden" value="' + full.id + '">'
                  // + '<button class="btn btn-primary btn-xs tab-edit" data-type="edit" data-loading-text="加载中..." type="button" title="编辑"><i class="fa fa-edit"></i></button>'
                  + '<button class="btn btn-success btn-xs tab-preview" data-type="preview" data-role="' + full.creativeType + '" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" type="button" title="' + VAM.j('creative preview') + '"><i class="fa fa-eye"></i></button>'
                  + '<button class="btn btn-warning btn-xs tab-unlink" data-type="unlink" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" type="button" title="' + VAM.j('unbind') + '"><i class="fa fa-unlink"></i></button>'
                  + '</div>';
          }
        }
      ],
      'initComplete': function() {
        var tableResize = new VamDataTable().columnResize($dataTable);
      }
    };
    $dataTable
    .on('preXhr.dt', function(evt) {
      $loadingWrap.show();
    });
    listTable = new VamDataTable().dataTables($dataTable, tableOptions);
    // After table data list.
    listTable.on('xhr.dt', function(evt) {
      $loadingWrap.fadeOut();
    });

    $dataTable.on('click', 'tbody td .tab-unlink', function (evt) {
      var $me = $(this),
        $rowInfo = $me.siblings('.row-info'),
        opId = $rowInfo.val(),
        opType = $me.data('type'),
        opData;
      evt.preventDefault();
      opData = {
        id: opId,
        type: opType
      };
      BootstrapDialog.confirm({
        title: VAM.j('Unbind Creative'),
        message: VAM.j('Confirm to unbind the creative?'),
        type: BootstrapDialog.TYPE_DANGER,
        closable: true, 
        draggable: true,
        btnCancelLabel: VAM.j('Cancel'),
        btnOKLabel: VAM.j('OK'),
        btnOKClass: 'btn-danger', 
        callback: function(result) {
          if(result) {
            VamListOp.listOp({
              url: dataUnlinkOp,
              data: opData,
              before: function () {
                $me.button('loading');
              },
              success: function (data) {
                if (data.status === 'success') {
                  VamOpMsg.messager(data);
                  listTable.ajax.reload();
                } else {
                  VamOpMsg.messager(data);
                }
              },
              always: function () {
                $me.button('reset');
              }
            });
          }else {
          }
        }
      });
    });

    $creativePreviewModal.on('hidden.bs.modal', function (evt) {
      // dataList.ajax.reload();
      $creativePreviewIfr.prop('src', '');
    });

    $dataTable.on('click', 'tbody td .tab-preview', function(evt) {
      var $me = $(this),
      $rowInfo = $me.siblings('.row-info'),
      opId = $rowInfo.val(),
      opType = $me.data('type'),
      opRole = $me.data('role'),
      opData, creativeIfrUrl,
      previewOpUrl;
      evt.preventDefault();
      
      if (opRole === 'banner') {
        previewOpUrl = VAM.getVar('LIST_PREVIEW_OP_URL');
      } else if (opRole === 'video'){
        previewOpUrl = VAM.getVar('LIST_PREVIEW_VIDEO_OP_URL');
      } else if (opRole === 'cpe') {
        previewOpUrl = VAM.getVar('LIST_PREVIEW_CPE_OP_URL');
      }

      creativeIfrUrl = previewOpUrl + '?id=' + opId + '&type=' + opRole + '&rnd=' + (new Date()).getTime();
      BootstrapDialog.show({
        title: VAM.j('Creative Preview'),
        size: BootstrapDialog.SIZE_WIDE,
        message: $('<iframe id="creative-preview-ifr" frameborder="0" style="width: 100%; min-height: 800px;" src="' + creativeIfrUrl + '"></iframe>'),
        buttons: [{
          label: VAM.j('Close'),
          cssClass: 'btn-default',
          action: function(dialogItself) {
            dialogItself.close();
          }
        }]
      });
    });

    // Add new strategy banner creative.
    var $newBtn = $('#new-operate-btn'),
      creativeIfrUrl = VAM.getVar('CREAITVE_IFR_URL');

    $newBtn.on('click', function (evt) {
      var $me = $(this);
      evt.preventDefault();
      BootstrapDialog.show({
        title: VAM.j('New Creative'),
        size: BootstrapDialog.SIZE_WIDE,
        cssClass: 'creative-preview-modal',
        message: $('<iframe class="creative-preview-ifr" frameborder="0" src="' + creativeIfrUrl + '"></iframe>'),
        buttons: [{
          label: VAM.j('Close'),
          cssClass: 'btn-default',
          action: function(dialogItself) {
            dialogItself.close();
          }
        }],
        onhidden: function(dialogItself){
          listTable.ajax.reload();
          dialogItself.close();
        }
      });
    });

    // Add new strategy video creative.
    var $newVideoBtn = $('#new-video-operate-btn'),
      creativeVideoIfrUrl = VAM.getVar('CREAITVE_VIDEO_IFR_URL');

    $newVideoBtn.on('click', function (evt) {
      var $me = $(this);
      evt.preventDefault();
      BootstrapDialog.show({
        title: VAM.j('New Video Creative'),
        size: BootstrapDialog.SIZE_WIDE,
        cssClass: 'creative-preview-modal',
        message: $('<iframe class="creative-preview-ifr" frameborder="0" src="' + creativeVideoIfrUrl + '"></iframe>'),
        buttons: [{
          label: VAM.j('Close'),
          cssClass: 'btn-default',
          action: function(dialogItself) {
            dialogItself.close();
          }
        }],
        onhidden: function(dialogItself){
          listTable.ajax.reload();
          dialogItself.close();
        }
      });
    });

    // Add New Strategy CPE Creative.
    var $newCpeBtn = $('#new-cpe-operate-btn'),
      creativeCpeIfrUrl = VAM.getVar('CREAITVE_CPE_IFR_URL');

    $newCpeBtn.on('click', function (evt) {
      var $me = $(this);
      evt.preventDefault();
      BootstrapDialog.show({
        title: VAM.j('New CPE Creative'),
        size: BootstrapDialog.SIZE_WIDE,
        cssClass: 'creative-preview-modal',
        message: $('<iframe class="creative-preview-ifr" frameborder="0" src="' + creativeCpeIfrUrl + '"></iframe>'),
        buttons: [{
          label: VAM.j('Close'),
          cssClass: 'btn-default',
          action: function(dialogItself) {
            dialogItself.close();
          }
        }],
        onhidden: function(dialogItself){
          listTable.ajax.reload();
          dialogItself.close();
        }
      });
    });
    // Add new strategy overlay creative.
    var $newOverlayBtn = $('#new-overlay-operate-btn'),
      creativeOverlayIfrUrl = VAM.getVar('CREAITVE_OVERLAY_IFR_URL');

    $newOverlayBtn.on('click', function (evt) {
      var $me = $(this);
      evt.preventDefault();
      BootstrapDialog.show({
        title: VAM.j('New Overlay Creative'),
        size: BootstrapDialog.SIZE_WIDE,
        cssClass: 'creative-preview-modal',
        message: $('<iframe class="creative-preview-ifr" frameborder="0" src="' + creativeOverlayIfrUrl + '"></iframe>'),
        buttons: [{
          label: VAM.j('Close'),
          cssClass: 'btn-default',
          action: function(dialogItself) {
            dialogItself.close();
          }
        }],
        onhidden: function(dialogItself){
          listTable.ajax.reload();
          dialogItself.close();
        }
      });
    });

    // Bind current creative.
    var $bindCreativeFrm = $('#bind-creative-frm'),
    $submitBtn = $bindCreativeFrm.find('button[type="submit"]'),
    $bindCreativeDataTable = $('#bind-creative-table'),
    $bindOpBtn = $('#bind-creative-btn'),
    $bindCreativeModal = $('#bind-creative-modal'),
    bindCreativeUrl = VAM.getVar('BIND_CREAITVE_URL'),
    bindCreativeList, bindCreativeTableOptions = {};

    bindCreativeTableOptions = {
      'dom': 'lrftip',
      'autoWidth': false,
      'ajax': {
        'url': bindCreativeUrl
      },
      'order': [0,'desc'],
      'columns': [
        {'data': 'id'},
        {'data': 'name'},
        {'data': 'creativeType'},
        {'data': 'materialType'},
        {'data': 'creativeSize'},
        {'data': 'vocation'},
        {'data': 'operate'}
      ],
      'columnDefs': [
        {
          'targets': [0,1,4],
          'render': function (data, type, full, meta) {
            return '<p title="' + data + '">' + data +'</p>'
          }
        },
        {
          'targets': 2,
          'render': function (data, type, full, meta) {
            var result = '', more = '';
            if (data === 'banner') {
              result = 'banner';
            } else if (data === 'video') {
              result = 'video';
            } else {
              result = 'cpe';
            }
            return '<p title="' + result + '">' + result +'</p>';
          }
        },
        {
          'targets': 3,
          'render': function (data, type, full, meta) {
            var result = '', more = '';
            if (data === 'static-pic') {
              result = VAM.j('Static Pic');
            } else if (data === 'dynamic-pic') {
              result = VAM.j('Dynamic Pic');
            } else if (data === 'swf' && full.creativeType === 'banner') {
              result = 'SWF';
            } else if (data === 'txt') {
              result = VAM.j('Text Chain');
            } else if (data === 'swf' && full.creativeType === 'video') {
              result = 'SWF';
            } else if (data === 'flv') {
              result = 'FLV';
            } else if (data === 'mp4') {
              result = 'MP4';
            }
            if (full.creativeType === 'video') {
              more = '<p title="' + full.duration + '">' + VAM.j('Duration') + '：' + full.duration +'s</p>';
            } else if (full.creativeType === 'cpe') {
              var cpeVideoType = full.cpeMaterialType.split(','),
                  videoType = [], meType = '';
              for (var i = 0; i < cpeVideoType.length; i++) {
                if (cpeVideoType[i] === 'mp4') {
                  meType = 'MP4';
                } else if (cpeVideoType[i] === 'ogg' || cpeVideoType[i] === 'ogv') {
                  meType = 'OGV';
                } else if (cpeVideoType[i] === 'webm') {
                  meType = 'WebM';
                } else if(cpeVideoType[i] === 'flv'){
                  meType = 'FLV';
                };
                videoType.push(meType);
              };
              videoType = videoType.join(',');
              more = '<p title="' + full.cpeMaterialType+ '">' + videoType +'</p>';
            };
            return '<p title="' + result + '">' + result +'</p>' + more;
          }
        },
        {
          'targets': 5,
          'render': function (data, type, full, meta) {
            var result = '', record = '', item;
            for (var i = 0, len = data.length; i < len; i++) {
              item = data[i];
              record = '<p class="text-success"><span class="label label-default">' + item['channel'] + '</span> ' + item['tags'] + '</p>';
              result += record;
            };
            return result;
          }
        },
        {
          'targets': -1,
          'render': function (data, type, full, meta) {
            var result = '', checked = '';
            checked = full.status === 'checked' ? 'checked' : '';
            result = '<div class="checkbox"><label><input class="ckb-children" type="checkbox" name="creative_id[]" value="' + full.id + '" ' + checked + '>&nbsp;&nbsp;' + VAM.j('bind') + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></div>';
            return result;
          }
        }
      ],
      'vamSettings': {
        'vamListDateFilter': true,
        'vamColumnFilter': false,
        'vamColumnResize': {
          'resize': true,
          'adjust': true
        }
      }
    };

    // SL.fn.CkbCascade($bindCreativeDataTable);
    bindCreativeList = new VamDataTable().dataTables($bindCreativeDataTable, bindCreativeTableOptions);

    $bindCreativeModal.on('shown.bs.modal', function (evt) {
      var $me = $(this);
      $bindOpBtn.button('reset');
    });

    $bindCreativeModal.on('hidden.bs.modal', function (evt) {
      listTable.ajax.reload();
    });

    $bindCreativeModal.on('click','.ckb-all',function(){
      var $me = $(this),
        status = this.checked;
      $('#bind-creative-modal').find('.ckb-children').prop('checked', status);
    });
    
    $bindCreativeModal.on('change','.ckb-children',function(){
      var $me = $(this),
          $all = $me.parents('#bind-creative-modal').find('.ckb-all'),
          allCkbLength = $me.parents('#bind-creative-modal').find('.ckb-children').length,
          haveCkbLength = $me.parents('#bind-creative-modal').find('.ckb-children:checked').length;
          if (allCkbLength === haveCkbLength) {
            $all.prop('checked',true);
          } else {
            $all.prop('checked',false);
          }
    });

    $bindCreativeFrm.submit(function () {
      var $me = $(this);
      $me.ajaxSubmit({
        beforeSubmit: function() {
          $submitBtn.button('loading');
        },
        success: function (data) {
          $submitBtn.button('reset');
          if (data.status === 'success') {
            VamOpMsg.messager(data);
            $bindCreativeModal.modal('hide');
            bindCreativeList.ajax.reload();
          } else {
            VamOpMsg.messager(data);
          }
        }
      });
      return false;
    });

    $bindOpBtn.on('click', function (evt) {
      var $me = $(this);
      evt.preventDefault();
      $me.button('loading');
      $bindCreativeModal.modal('show');
    });
    
    //create creative table rc-handle
    $bindCreativeModal.on('shown.bs.modal', function(){
      var creativeTableResize = new VamDataTable().columnResize($bindCreativeDataTable); 
    });
  });
  $(function () {
    var $dataFrm = $('#data-frm'),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      $operateBtn = $submitBtn.filter('.save-btn'),
      $operateType = $dataFrm.find('.operate-type');

    $submitBtn.on('click', function (evt) {
     var $me = $(this),
          operate = $me.data('operate'),
          operateTxt;
        operateTxt = '.' + operate + '-btn';
        $operateBtn = $submitBtn.filter(operateTxt);
        $operateType.val(operate);
    });
    $dataFrm.submit(function () {
      var $me = $(this);
      $me.ajaxSubmit({
        beforeSubmit: function() {
          $operateBtn.button('loading');
        },
        success: function (data) {
          var next = $operateBtn.data('operate');
          $operateBtn.button('reset');
          if (data.status === 'success') {
            VamOpMsg.messager(data);
            if (next === 'save-next') {
              window.location.href = VAM.getVar('NEXT_URL');
            } else {
              window.location.href = 'solution-list';
            };
          } else {
            VamOpMsg.messager(data);
          }
        }
      });
      return false;
    });
  });
});
